<?php

include_once 'config.php';

$username = 'tungt'; 
function percent($num_amount, $num_total) {
	$count1 = $num_amount / $num_total;
	$count2 = $count1 * 100;
	$count = number_format($count2, 2);
	return  $count.'%';
}
function get_profit_stock($username,$DB_NAME,$offset,$limit){

	$db=new SQLiteDatabase($DB_NAME);

	$real_name= sqlite_escape_string($username);

	$result=$db->query("SELECT stock, transaction_type, sum(quality),sum(value*quality) FROM stock_history where username='$real_name' group by stock, transaction_type order by stock asc,transaction_type asc limit $limit offset  $offset");

	$rs = array();

	while($result->valid()) {

		$row=$result->current();

		$rs[] =$row;

		$result->next();

	}

	return $rs;

} 

?>
<?php

$rs = get_profit_stock($username, $DB_NAME,0,10);
$sum = 0;
$previous_stock = null;
$previous_total =0; 
$previous_total_2 =0; 
?>
<table border="1">

	<thead>

		<tr>

			<th scope="col">stock</th>

			<th scope="col">type</th>

			<th scope="col">sum quality</th>

			<th scope="col">sum total</th>
			
		</tr>

	</thead>

	<tbody>

		<?php

	foreach ($rs as $r) {
		if($r[0] == $previous_stock){
			//same stock, difference type
			$previous_total = $r[3] - $previous_total;
		}else{
			//difference stock
		if(!is_null($previous_stock)){
				//print a total
				echo "<tr>

			<td colspan='2'>Profit</td>

			<td colspan='2'>".number_format($previous_total)."(".percent($previous_total, $previous_total_2).")"."</td>

		</tr>";
				$sum  = $sum + $previous_total;
			}
			$previous_stock = $r[0];
			$previous_total = $r[3];
			$previous_total_2 = $r[3];
		}
		echo "<tr>

			<td>".$r[0]."</td>

			<td>".$r[1]."</td>

			<td>".number_format($r[2])."</td>

			<td>".number_format($r[3])."</td>

		</tr>";

	}
	//in luot cuoi
	if(!is_null($previous_stock)){
				//print a total
				echo "<tr>

			<td colspan='2'>Profit</td>

			<td colspan='2'>".number_format($previous_total)."(".percent($previous_total, $previous_total_2).")"."</td>

		</tr>";
				$sum  = $sum + $previous_total;
	}
    echo "<tr>

			<td colspan='2'>Total Profit</td>

			<td colspan='2'>".number_format($sum)."</td>

		</tr>";
		?>
	
	</tbody>

</table>

